package com.bcu.cn.onlineexamsystem.exammanage.service.impl;

import com.bcu.cn.onlineexamsystem.exammanage.entity.ExamReviewDTO;
import com.bcu.cn.onlineexamsystem.exammanage.entity.ReviewSubmitDTO;
import com.bcu.cn.onlineexamsystem.exammanage.mapper.ExamReviewMapper;
import com.bcu.cn.onlineexamsystem.exammanage.service.ExamReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class ExamReviewServiceImpl implements ExamReviewService {

    @Autowired
    private ExamReviewMapper examReviewMapper;

    @Override
    public List<ExamReviewDTO> getPendingExams(String teacherId) {
        return examReviewMapper.findPendingExamsByTeacher(teacherId);
    }

    @Override
    public ExamReviewDTO getExamReviewDetail(Long recordId) {
        // 直接根据recordId获取考试基本信息
        ExamReviewDTO examReview = examReviewMapper.findExamByRecordId(recordId);
        
        if (examReview == null) {
            throw new RuntimeException("未找到对应的考试记录");
        }
        
        // 获取答题详情
        List<ExamReviewDTO.AnswerReviewDTO> answers = examReviewMapper.findAnswersByRecordId(recordId);
        examReview.setAnswers(answers);
        
        return examReview;
    }

    @Override
    public ExamReviewDTO getExamReviewDetail(Long recordId, String teacherId) {
        // 根据recordId和teacherId获取考试基本信息（带权限验证）
        ExamReviewDTO examReview = examReviewMapper.findExamByRecordIdAndTeacher(recordId, teacherId);
        
        if (examReview == null) {
            throw new RuntimeException("未找到对应的考试记录或无权限访问");
        }
        
        // 获取答题详情
        List<ExamReviewDTO.AnswerReviewDTO> answers = examReviewMapper.findAnswersByRecordId(recordId);
        examReview.setAnswers(answers);
        
        return examReview;
    }

    @Override
    @Transactional
    public void submitReview(ReviewSubmitDTO reviewSubmitDTO) {
        BigDecimal totalScore = BigDecimal.ZERO;
        
        // 更新每道题的分数和评语
        for (ReviewSubmitDTO.AnswerScoreDTO answerScore : reviewSubmitDTO.getAnswers()) {
            examReviewMapper.updateAnswerScore(
                answerScore.getAnswerId(), 
                answerScore.getScore(), 
                answerScore.getTeacherComment()
            );
            
            // 累加总分
            if (answerScore.getScore() != null) {
                totalScore = totalScore.add(answerScore.getScore());
            }
        }
        
        // 更新考试记录的总分
        examReviewMapper.updateExamTotalScore(reviewSubmitDTO.getRecordId(), totalScore);
    }
} 